<?php

/**
 * 
 * JSAPI支付实现类
 * 该类实现了从微信公众平台获取code、通过code获取openid和access_token、
 * 生成jsapi支付js接口所需的参数、生成获取共享收货地址所需的参数
 * 
 * 该类是微信支付提供的样例程序，商户可根据自己的需求修改，或者使用lib中的api自行开发
 * 
 * @author widy
 *
 */
class ControllerCommonWxLogin extends Controller
{
  public function index() {
    if (isset($this->session->data['weixin_login_openid'])) {
      return;
    }

    if (isset($this->request->get['route'])&&substr($this->request->get['route'], 0, 3) == 'api') {
      return;
    }

    $oauth = new WxOauth();
    $url = urlencode(HTTP_SERVER.'system/weixin/wx_oauth.php');
    // $url = urlencode('http://xebxhmwxai.localtunnel.me/~lqn/bhz/system/weixin/wx_oauth.php');
    $oauth->init($url);
    //通过code获得openid
    if (!isset($_GET['code'])){   
      if (isset($this->request->get['route'])) {
        $this->session->data['wx_login_redir_url'] = $this->request->get['route'];
        $get_params = $this->request->get;
        unset($get_params['route']);
        if(!empty($get_params)) {
          $this->session->data['wx_login_redir_param'] = $get_params;
        }
      }
      $url = $oauth->get_code_by_authorize(1);
      exit();
    } else {
      //获取code码，以获取openid
      $code = $_GET['code'];
      $user_info = $oauth->get_userinfo_by_authorize($code);
      //Login user
      if (isset($this->session->data['wx_login_redir_url'])){
        $wx_redir_params = '';
        if(!empty($this->session->data['wx_login_redir_param'])) {
          foreach ($this->session->data['wx_login_redir_param'] as $key => $value) {
            $wx_redir_params .= $key . '=' . $value . '&';
          }
          $wx_redir_params=substr($wx_redir_params,0,strlen($wx_redir_params)-1);
        }
        $url = $this->url->link($this->session->data['wx_login_redir_url'], $wx_redir_params, 'SSL');
        unset($this->session->data['wx_login_redir_url']);
        unset($this->session->data['wx_login_redir_param']);
      }
      else {
        $url = $this->url->link('common/index', '', 'SSL') . '#home';
      }
      if($user_info && $user_info['openid']){
        $this->session->data['weixin_login_openid'] = $user_info['openid'];
        $this->session->data['weixin_avatar'] = $user_info['headimgurl'];
        //尝试使用openid登录用户
        $this->customer->loginByWx($user_info['openid']);
        // var_dump($user_info);die();
        // header("Location: $url");
        $this->response->redirect($url);
      }
      else{
        throw new Exception('Oauth 失败');
      }
    }
  }
}